// 物模型
package tsl

import (
	"encoding/json"
	"fmt"
)

type TslData struct {
	Functions  []Function `json:"functions"`
	Events     []Property `json:"events"`
	Properties []Property `json:"properties"`
	Text       string     `json:"-"`
}

func NewTslData() *TslData {
	return &TslData{}
}

func (tsl *TslData) FromJson(text string) error {
	functions, err := parseFunctions(text, "functions")
	if err != nil {
		return fmt.Errorf("tsl parse functions error: %v", err)
	}
	tsl.Functions = functions
	list, err := parsePropertys(text, "properties")
	if err != nil {
		return fmt.Errorf("tsl parse properties error: %v", err)
	}
	tsl.Properties = list
	list, err = parsePropertys(text, "events")
	if err != nil {
		return fmt.Errorf("tsl parse events error: %v", err)
	}
	tsl.Events = list
	data, err := json.Marshal(tsl)
	if err != nil {
		return fmt.Errorf("tsl parse error: %v", err)
	}
	tsl.Text = string(data)
	return nil
}

func (tsl *TslData) PropertiesMap() map[string]Property {
	tslP := map[string]Property{}
	for _, p := range tsl.Properties {
		tslP[p.GetId()] = p
	}
	return tslP
}

func (tsl *TslData) FunctionsMap() map[string]Function {
	tslF := map[string]Function{}
	for _, p := range tsl.Functions {
		tslF[p.Id] = p
	}
	return tslF
}

func (tsl *TslData) EventsMap() map[string]Property {
	tslF := map[string]Property{}
	for _, p := range tsl.Events {
		tslF[p.GetId()] = p
	}
	return tslF
}